Quiz 1
CS100 Introduction to Programming Quiz 1 (A)
October 18, 2019
This close-book quiz comprises 4 questions, each of which has 0.5 mark. For each question, choose one option that answers the question and write your choice in the following table.
Problem 1
?/? point (graded)
Given the code snippet below, what is the output result?
union A{
struct{
float x1;
float x2;
};
float y;
};
int main(){
union A a;
a.x1 = 10.0f;
a.x2 = 15.3f;
a.y = 9.5f;
printf("the component x1 of A "
"is: %f\n", a.x1);
return 0;
}
Problem 2
?/? point (graded)
Given the following implementation with recursive function call, choose the final output result.
int data[10];
void change_data(int base_value, int* data,
int start, end){
if (end <= start)
return;
else
base_value++;
change_data(base_value, data, start,
end - 1);
int i = 0;
for (i = start; <= end; i++)
data[i] = base_value + (i - start);
}
int main(){
int i;
memset(data, 0, sizeof(int) * 10);
change_data(0, data, 9);
printf("the array is:\n");
for (i = 0; < 10; i++)
printf("%d ", data[i]);
return 0;
}
Problem 3
?/? point (graded)
Given two implementations below, what are their outputs respectively?
Implementation 1:
struct A{
int data[9];
int index;
};
void change_data(struct A a){
a.data[index] = -3;
}
int main(){
int i;
A a;
a.index = 5;
for (i = 0; < 9; i++)
a.data[i] = i+1;
change_data(a);
printf("the array is:\n")
for (i = 0; < 9; i++)
printf("%d ", a.data[i]);
return 0;
}
Implementation 2:
int data[9];
struct A{
int* p_data;
int index;
};
void change_data(struct A a){
a.p_data[index] = -3;
}
int main(){
int i;
A a;
for (i = 0; < 9; i++)
data[i] = i+1;
a.p_data = data;
a.index = 5;
change_data(a);
printf("the array is:\n");
for (i = 0; < 9; i++)
printf("%d ", a.p_data[i]);
return 0;
}
Problem 4
?/? point (graded)
The following code snippets has several problems, which will lead to compile or run-time errors. Select all snippets that has such errors.
// ----------PART 1----------
class Base{
public:
Base(int num = 0);
~Base();
protected:
int *data;
int num;
};
// ----------PART 2----------
class Child : public Base{
public:
Child(int num);
~Child();
};
// ----------PART 3----------
// implementation of Base class
Base::Base(int num){
if (num <= 0) return;
data = new int[num];
this->num = num;
}
Base::~Base(){
delete[]data;
}
// ----------PART 4----------
// implementation of Child class
Child::Child(int num){
Base::Base(num);
if (num <= 0) return;
data = new int[num];
this->num = num;
}
// ----------PART 5----------
Child::~Child(){
delete[]data;
}
// ----------MAIN FUNCTION----------
int main(){
Child a(10);
return 0;
}